package com.pan.entity;

import java.awt.event.ActionListener;
import java.util.LinkedHashMap;
import java.util.Map;

public class HumbleHttpResponse {
    /**
     "HTTP/1.1 200 OK"
     "Content-Type: text/html; charset=utf-8"
     "Server: HumbleHTTPServer"
     "Connection: close"
     "" // 返回头和正文之间的空行 This is the Header And Content Null Line
     "<html><h1> Hello <h1></html>"
     *
     */
    private Map<String,String> AttributeMap;
    private int code;
    {
        code = 200;
        AttributeMap = new LinkedHashMap<>();
        AttributeMap.put("Content-Type","text/html; charset=utf-8");
        AttributeMap.put("Connection","close");
    }

    private String body = null;
    public void setBody(String body){
        int length = body.length();
        AttributeMap.put("Content-Length",""+length);
        this.body = body;
    }

    public void setAttributeMap(String attrName , String attrValue) {
        AttributeMap.put(attrName,attrValue);
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String toString(){
        String httpMessage = "HTTP/1.1 200 OK"+ "\r\n"+
                "Server: HumbleHTTPServer"+"\r\n"+
                AttributeMap.entrySet().stream().map(kv->kv.getKey()+": "+kv.getValue()+"\r\n").reduce((a,b)->a+b).get() +
                "\r\n" + (body==null?"":body);
        return httpMessage;
    }

}
